<template>
  <Dialog title="上传凭据" v-model="dialogVisible" :width="isMobile() ? '80%' : '30%'">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="凭据" prop="img">
        <UploadImg v-model="formData.img" height="80px" width="100%" class="min-w-160px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InvoiceApi } from '@/api/ai/invoice'
import { UploadImg } from '@/components/UploadFile'
import { isMobile } from '@/utils/isMobile'

/** 发票信息 表单 */
defineOptions({ name: 'UploadImg' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  img: undefined,
  status: ''
})
const formRules = reactive({
  img: [{ required: true, message: '凭据不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id) => {
  dialogVisible.value = true
  resetForm()
  formData.value = await InvoiceApi.getInvoice(id)
  debugger
  // 修改时，设置数据
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  formData.value.status = '已开票'
  await InvoiceApi.updateInvoice(formData.value)
  message.success(t('common.updateSuccess'))
  dialogVisible.value = false
  emit('success')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    img: undefined,
    status: ''
  }
  formRef.value?.resetFields()
}
</script>
